/***
 * 自定义promise方法
 * @params { executor } Function
 */
function CustomizePromise(executor) {
    const self = this
    self.status = "pending" // 待定状态
    self.value = null   //成功的返回数据
    self.reason = null  //失败的返回原因
    //解决异步问题,暂存;发布订阅模式
    self.onFulfilledCallbacks = []
    self.onRejectedCallbacks = []
    /**
     * 2、返回成成功结果
     *    执行依赖
     */
    function resolve(value) {
        if (self.status === 'pending') {
            self.value = value
            self.status = "fulfilled"
            /***状态改变 */
            self.onFulfilledCallbacks.forEach(callback => callback(value))
        }
    }
    /**
     * 3、返回失败结果
     *    执行依赖
     */
    function reject(reason) {
        if (self.status === 'pending') {
            self.status = "rejected"
            self.reason = reason
            /***状态改变 */
            self.onRejectedCallbacks.forEach(callback => callback(reason))
        }
    }

    /**
     * 4、excutor =>立即执行
     */
    try {
        executor && executor(resolve, reject)
    } catch (error) {
        reject(error)
    }
}

/**
 * promise then方法:收集依赖
 */
CustomizePromise.prototype.then = function (onFulfilled, onRejected) {
    onFulfilled = typeof onFulfilled === 'function' ?
        onFulfilled : function (resolve) { resolve(data) }
    onRejected = typeof onRejected === 'function' ?
        onRejected : function (reject) { reject(data) }
    const self = this
    if (self.status === 'pending') {
        self.onFulfilledCallbacks.push(onFulfilled)
        self.onRejectedCallbacks.push(onRejected)
    }
}


const demo = new CustomizePromise((resolve, reject) => {
    console.log("==========打印=========")
    //异步任务
    setTimeout(() => {
        console.log("==========打印1=========")
        resolve(2222)
    }, 200)
})
console.log("demo:", demo)
demo.then(res => console.log("res:", res)) //res: 2222
/**
 * 执行结果：
   ==========打印=========
   demo: CustomizePromise {status: 'pending', value: null, reason: null, onFulfilledCallbacks: Array(0), onRejectedCallbacks: Array(0)}
   ==========打印1=========
   res: 2222
 */